﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Configuration;
using dooll.Common;
namespace dooll.AdminPassport
{

    public partial class AdminLogin : System.Web.UI.Page
    {
       
        private dooll.Config.AppConfigInfo XCAC = dooll.Config.AppConfig.load();
        bool bIsAjax = false;
        protected void Page_Load(object sender, EventArgs e)
        {
                //防止网页后退--禁止缓存
            Response.Expires = 0;
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            Response.AddHeader("pragma", "no-cache");
            Response.CacheControl = "no-cache";

            string sUserName = Request.Form["mLoginUid"];         //用户名
            string sPassWord = Request.Form["mLoginPwd"];        //密码
            string sValidCode = Request.Form["vCode"];       //填写的验证码
            string sActiveCode = Request.Form["ActiveCode"];            //填写的验证码
            string sReturnUrl = Request.Form["toUrl"];                  //登录成功转向
 
            string sIsAjax = Request.Form["IsAjax"];                    // 是否AJAX
            bIsAjax = (string.IsNullOrEmpty(sIsAjax) || (sIsAjax != "1")) ? false : true; //是否AJAX
            

            if (!(string.IsNullOrEmpty(sUserName) && string.IsNullOrEmpty(sPassWord)))
            {

                #region 验证码处理
                if (sValidCode != null && sValidCode.Length == 4)
                {
                    if (Request.Cookies["CheckCode"] == null)
                    {
                        Response.Write(jsAlert(500, "浏览器不支持Cookie或是未生成验证码!", 1, null));
                        Response.End();
                    }
                    string strCode = Request.Cookies["CheckCode"].Value;
                    if (string.IsNullOrEmpty(strCode) || sValidCode != strCode)
                    {
                        Response.Write(jsAlert(403, "提示:请输入正确的验证码!", 1, null));
                        Response.End();
                    }
                }
                else
                {
                    Response.Write(jsAlert(403, "提示:请输入正确的验证码!", 1, null));
                    Response.End();
                }
                #endregion

                sUserName = sUserName.Trim();

                if (string.IsNullOrEmpty(sUserName) || sUserName.Length < 1)
                {
                    Response.Write(jsAlert(403,"提示:请输入正确的用户名（至少1位）!", 1, null));
                    Response.End();
                }

                if (string.IsNullOrEmpty(sPassWord) && sPassWord.Length < 3)
                {
                    Response.Write(jsAlert(403,"提示:请输入正确的密码（至少三位）!", 1, null));
                    Response.End();
                }
                doLogin(sUserName, sPassWord, sReturnUrl, sActiveCode);

            }

        }
        protected void doLogin(string sUserName, string sPassWord, string sReturnUrl, string sActiveCode)
        {
            Common.AdminInfo AdminPa;
            AdminManage AM  ;
            try
            {
                string strIp = Request.ServerVariables["remote_addr"];

                AM = new AdminManage("default");
                AdminPa = AM.Login(sUserName, sPassWord, strIp);


                
                
                if (AdminPa != null)
                {
                    if (AdminPa.IsLogin)
                    {
                        #region 登录成功


                        //产生令牌
                        string tokenValue = AdminPa.Token;

                        //tokenCookie.Domain = "passport.com";
                        //Response.AppendCookie(tokenCookie);

                        //产生主站凭证
                        //object info = true;

                        string PaValue = Newtonsoft.Json.JavaScriptConvert.SerializeObject(AdminPa);

                        int timeout = (string.IsNullOrEmpty(ConfigurationManager.AppSettings["timeout"])) ? 20 : int.Parse(ConfigurationManager.AppSettings["timeout"]);
                        AdminCacheManager ACM = new AdminCacheManager();
                        if (!ACM.TokenInsert(tokenValue, PaValue, timeout, Request.ServerVariables["HTTP_REFERER"], strIp,  sUserName))
                        {
                            /*无法写入数据库操作*/
                            Response.Write(jsAlert(ACM.ErrInfo, 1, null));
                            return ;
                        }
                        else
                        {
                            /*写入Cookie令牌*/
                            //string tokenValue = this.getGuidString();
                            HttpCookie tokenCookie = new HttpCookie(XCAC.PassportTokenCookie);
                            tokenCookie.Values.Add("Value", tokenValue);
                            Response.AppendCookie(tokenCookie);
                        }

                        ACM = null;

                        
                        //带主站令牌跳转回分站
                        if (string.IsNullOrEmpty(sReturnUrl))
                        {
                            sReturnUrl = Request.ServerVariables["HTTP_REFERER"];
                            if(string.IsNullOrEmpty(sReturnUrl)){
                                Response.Write(jsAlert("你已经登录成功！", 1, null));
                            }

                        }else if(sReturnUrl.StartsWith("/") && Request.UrlReferrer!=null){
                            sReturnUrl = string.Concat("http://", Request.UrlReferrer.Host,(Request.UrlReferrer.Port ==80)?"":(":"+Request.UrlReferrer.Port.ToString()),sReturnUrl);
                        }

                        Response.Redirect(getTokenURL(sReturnUrl, tokenValue),false);
                        #endregion
                    }
                    else
                    {
                        Response.Write(jsAlert(500, AM.ErrMessage, 1, null));
                        return ;
                    }

                }
                else
                {
                    Response.Write(jsAlert(500, AM.ErrMessage, 1, null));
                    return ;
                }
                
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return;
            }
            AM = null;
            AdminPa = null;

        }
        public string SessionID()
        {
            string SessionCookieName = "_dooll_SessionId_";  
            if (Request.Cookies[SessionCookieName]==null||string.IsNullOrEmpty(Request.Cookies[SessionCookieName].Value))
            {
                HttpCookie cookieSession = new HttpCookie(SessionCookieName, Session.SessionID);
                Response.AppendCookie(cookieSession);
            }
            return Request.Cookies[SessionCookieName].Value;
        }

        /// <summary>
        /// 产生绝对唯一字符串，用于令牌
        /// </summary>
        /// <returns></returns>
        private string getGuidString()
        {
            return Guid.NewGuid().ToString().ToLower();
        }

        public void Alert(string strAlert, int type, string GoPage)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", jsAlert(strAlert, type, GoPage));
        }

        public void Alert(string strAlert)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", jsAlert(strAlert, 0, null));
        }

        #region javascript 提示功能
        /// <summary>
        /// javascript 提示功能
        /// </summary>
        /// <param name="strAlert">提示内容</param>
        /// <param name="type">0不操作,1退回 ,2转向页面,3关闭窗口,4刷新父级窗口关闭子窗口</param>
        /// <param name="GoPage">type=2 的转向页面</param>
        /// <returns>javascript 提示构成的字符串</returns>
        private string jsAlert(int State,string strAlert, int type, string GoPage)
        {
            if (bIsAjax)
            {
                //return string.Concat(State, ",", strAlert);
                return jsAlert(strAlert, 0, GoPage);
            }
            else
            {
                return jsAlert(strAlert, type, GoPage);
            }
        }
        private string jsAlert(string strAlert, int type, string GoPage)
        {
            string temp;
            temp = "<script type='text/javascript'>";
            temp += "alert('" + strAlert + "');";
            switch (type)
            {
                case 0:
                    break;
                case 1:
                    temp += "history.back();";
                    break;
                case 2:
                    temp += "location.href='" + GoPage + "';";
                    break;
                case 3:
                    temp += "window.close();";
                    break;
                case 4:
                    temp += "window.opener.location.reload();";
                    temp += "window.close();";
                    break;
                default:
                    temp += "";
                    break;
            }
            temp += "</script>";
            return temp;
        }
        #endregion

        /// <summary>
        /// 获取带令牌请求的URL
        /// 在当前URL中附加上令牌请求参数
        /// </summary>
        /// <returns></returns>
        private string getTokenURL(string toUrl,string TokenValue)
        {

            if (Common.Util.get_AppSettings("debug")== "1")
                Common.Util.toLog(Server.MapPath("/debug.log"), toUrl);
            UriBuilder  ub = new UriBuilder(toUrl);
            
            string[] s = ub.Query.Split("&".ToCharArray());
            
            string q = string.Concat("token=",TokenValue) ;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i].Split("=".ToCharArray())[0]!="token")
                {
                    string p = (s[i].IndexOf("?") == 0) ? s[i].Substring(1) : s[i];
                    q = string.Concat(q,"&",p) ;
                }
            }
            ub.Query = q;
            return ub.Uri.ToString ();
        }
    }
}